package com.hefan.robot.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.cat.common.entity.Page;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hefan.common.ons.TopicRegistry;
import com.hefan.common.ons.TopicRegistryDev;
import com.hefan.common.ons.TopicRegistryTest;
import com.hefan.common.ons.listener.GLLMessageListener;
import com.hefan.common.ons.service.ONSProducer;
import com.hefan.common.util.DynamicProperties;
import com.hefan.common.util.MapUtils;
import com.hefan.live.bean.LiveRoomPersonVo;
import com.hefan.live.bean.RobotListenerVo;
import com.hefan.live.itf.LiveLogService;
import com.hefan.live.itf.LivingRedisOptService;
import com.hefan.live.itf.RoomEnterExitOptService;
import com.hefan.robot.common.util.RandomUtil;
import com.hefan.robot.configCenter.RobotConfigCenter;
import com.hefan.user.bean.WebUser;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 真人触发机器人进出直播间
 * Created by nigle on 2016/12/7.
 */
@Component
public class RobotWhenLivingListener implements GLLMessageListener {

    Logger logger = LoggerFactory.getLogger(RobotWhenLivingListener.class);

    @Resource
    LivingRedisOptService livingRedisOptService;
    @Resource
    private RobotConfigCenter robotConfigCenter;
    @Resource
    LiveLogService liveLogService;
    @Resource
    RoomEnterExitOptService roomEnterExitOptService;
    @Resource
    ONSProducer onsProducer;

    @Override
    public TopicRegistry getTopicRegistry() {
        return TopicRegistry.HEFAN_ROBOT_WHEN_LIVING ;
    }

    @Override
    public TopicRegistryDev getTopicRegistryDev() {
        return TopicRegistryDev.HEFAN_ROBOT_WHEN_LIVING_DEV;
    }

    @Override
    public TopicRegistryTest getTopicRegistryTest() {
        return TopicRegistryTest.HEFAN_ROBOT_WHEN_LIVING_TEST;
    }

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        String realTopic = message.getTag();
        logger.info("直播中填充机器人-开始： receiver MessageListener topic: {}, realTopic : {}, msg_body: {}",
                message.getTopic(), realTopic, new String(message.getBody()));
        try {
            Map map = new ObjectMapper().readValue(message.getBody(), Map.class);
            if (null != map && !map.isEmpty()) {
                String voStr = (String) map.get("vo");
                RobotListenerVo vo = JSONObject.parseObject(voStr, RobotListenerVo.class);
                if (null == vo) {
                    logger.info("RobotListenerVo解析失败");
                    return Action.CommitMessage;
                }
                if (vo.getInOrOut() == 1){
                    logger.info("用户进入直播间触发::" + vo.getAnchId() + "::" +vo.getLiveUuid() );
                    return joinRoom(vo.getLiveUuid(),vo.getChatRoomId(),vo.getAnchId());
                } else if (vo.getInOrOut() == 0) {
                    logger.info("用户离开直播间触发::" + vo.getAnchId() + "::" +vo.getLiveUuid() );
                    return leftRoom(vo.getLiveUuid(), vo.getChatRoomId(), vo.getAnchId());
                }
                return Action.CommitMessage;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("HEFAN_ROBOT_WHEN_LIVING_DELAY receiver MessageListener ERROR：" + e.getMessage());
            return Action.CommitMessage;
        } finally {
            logger.info("HEFAN_ROBOT_WHEN_LIVING_DELAY receiver MessageListener END");
            return Action.CommitMessage;
        }
    }

    /**
     * 进入直播间
     */
    private Action joinRoom(String liveUuid, int chatRoomId, String anchId) {
        try {
            if (!livingRedisOptService.isExistsLivingInfo_Hash(anchId)){
                logger.info("直播已经结束，结束进入机器人");
                return Action.CommitMessage;
            }
            //更新直播间内真实人数
            livingRedisOptService.addLivingUserCountReal(anchId, 1);

            Map<String,String> propty = robotConfigCenter.getPublicConfig();
            //进入机器人的数量
            int robotCountMin = MapUtils.getIntValue(propty,"robot.enter.count.min",0);
            int robotCountMax = MapUtils.getIntValue(propty,"robot.enter.count.max",0);
            int robotCount = RandomUtil.getRandom(robotCountMin, robotCountMax + 1);
            int robotDelayMin = MapUtils.getIntValue(propty, "robot.delay.min", 30000);
            int robotDelayMax = MapUtils.getIntValue(propty, "robot.delay.max", 120000);
            int robotInOutMin = MapUtils.getIntValue(propty, "robot.enter.out.delay.time.min", 30000);
            int robotInOutMax = MapUtils.getIntValue(propty, "robot.enter.out.delay.time.max", 120000);
            int robotDelay = RandomUtil.getRandom(robotInOutMin, robotInOutMax);
            String onsEnv = MapUtils.getStrValue(propty, "ons.env", "");

            logger.info("直播间{}加入机器人{}个，发送MQ开始(用户进入触发)",anchId,robotCount);
            RobotListenerVo vo = new RobotListenerVo();
            vo.setAnchId(anchId);
            vo.setLiveUuid(liveUuid);
            vo.setChatRoomId(chatRoomId);
            vo.setInOrOut(1);
            int flag = RandomUtil.getRandom(1000, 5000);
            //机器人跟进的延时时间
            for (int i = 0; i < robotCount; i++) {
                com.hefan.common.ons.bean.Message message = new com.hefan.common.ons.bean.Message();
                vo.setInfo("机器人消费过滤主播ID：" + anchId + "正常机器人任务ID：" + flag + "--执行总次数：" + robotCount + "，本次第" + i + "个");
                message.put("vo", JSON.toJSONString(vo));
                message.setTopic(TopicRegistry.HEFAN_ROBOT_ENTER_EXIT_DELAY);
                message.setTag(onsEnv);
                onsProducer.sendDelayMsg(message, robotDelay);
                logger.info("发送MQ：{}直播间加入机器人(用户进入触发)，延时{}毫秒",anchId,robotDelay);
                robotDelay += RandomUtil.getRandom(robotDelayMin, robotDelayMax);
            }
            logger.info("直播间{}加入机器人{}个发送MQ结束(用户进入触发)",anchId,robotCount);
        } catch (Exception e) {
            logger.info("机器人进入直播间处理失败");
            e.printStackTrace();
        }
        return Action.CommitMessage;
    }

    /**
     * 离开直播间
     */
    private Action leftRoom(String liveUuid, int chatRoomId, String anchId) {
        try {

            if (!livingRedisOptService.isExistsLivingInfo_Hash(anchId)){
                logger.info("直播已经结束，结束离开机器人");
                return Action.CommitMessage;
            }
            //更新直播间内真实人数
            livingRedisOptService.decLivingUserCountReal(anchId, 1);

            Map<String,String> propty = robotConfigCenter.getPublicConfig();
            int robotCountMin = MapUtils.getIntValue(propty,"robot.exit.count.min",0);
            int robotCountMax = MapUtils.getIntValue(propty,"robot.exit.count.max",0);
            int robotCount = RandomUtil.getRandom(robotCountMin, robotCountMax + 1);
            String onsEnv = MapUtils.getStrValue(propty, "ons.env", "");
            int robotDelayMin = MapUtils.getIntValue(propty, "robot.delay.min", 30000);
            int robotDelayMax = MapUtils.getIntValue(propty, "robot.delay.max", 120000);
            int robotInOutMin = MapUtils.getIntValue(propty, "robot.enter.out.delay.time.min", 30000);
            int robotInOutMax = MapUtils.getIntValue(propty, "robot.enter.out.delay.time.max", 120000);
            int robotDelay = RandomUtil.getRandom(robotInOutMin, robotInOutMax);

            logger.info("发送MQ：{}直播间移除机器人{}个，发送MQ开始(用户进入触发)",anchId,robotCount);
            RobotListenerVo vo = new RobotListenerVo();
            vo.setAnchId(anchId);
            vo.setLiveUuid(liveUuid);
            vo.setChatRoomId(chatRoomId);
            vo.setInOrOut(0);
            int flag = RandomUtil.getRandom(1000, 5000);
            //机器人离开的延时时间
            for (int i = 0; i < robotCount; i++) {
                com.hefan.common.ons.bean.Message message = new com.hefan.common.ons.bean.Message();
                vo.setInfo("机器人消费过滤主播ID：" + anchId + "正常机器人任务ID：" + flag + "--执行总次数：" + robotCount + "，本次第" + i + "个");
                message.put("vo", JSON.toJSONString(vo));
                message.setTopic(TopicRegistry.HEFAN_ROBOT_ENTER_EXIT_DELAY);
                message.setTag(onsEnv);
                onsProducer.sendDelayMsg(message, robotDelay);
                logger.info("发送MQ：{}直播间移除机器人(用户进入触发)，延时{}毫秒",anchId,robotDelay);
                robotDelay += RandomUtil.getRandom(robotDelayMin, robotDelayMax);
            }
            logger.info("");
            logger.info("直播间移除机器人(用户离开触发){}个结束", robotCount);
        } catch (Exception e) {
            logger.info("离开直播间移除机器人失败");
        }
        return Action.CommitMessage;
    }
}
